package com.cz.zslu.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cz.zslu.common.ReturnObject;
import com.cz.zslu.entity.*;
import com.cz.zslu.interceptor.BaseContextHandler;
import com.cz.zslu.interceptor.IgnoreAuth;
import com.cz.zslu.model.TransactionRecord;
import com.cz.zslu.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单管理 前端控制器
 * </p>
 *
 * @author 森森
 */
@RestController
@RequestMapping("/sys/order")
@Api(description = "订单管理")
public class OrderController {
    @Autowired
    private IZslOrderService iZslOrderService;
    @Autowired
    private IZslCarService iZslCarService;
    @Autowired
    private IZslStoreCommodityService iZslStoreCommodityService;
    @Autowired
    private IZslShippingAddressService iZslShippingAddressService;
    @Autowired
    private IZslOrderCommodtyService iZslOrderCommodtyService;
    @Autowired
    private IZslOrderEvaluateService iZslOrderEvaluateService;
    @Autowired
    private IZslStoreService iZslStoreService;
    @Autowired
    private ISysUserService iSysUserService;


    @ApiOperation("单商品直接购买")
    @RequestMapping(value = "/addOrder", method = RequestMethod.POST)
    public ReturnObject addOrder(@ApiParam("商品id") @RequestParam Long commodityId,
                                 @ApiParam("商品数量") @RequestParam Integer count,
                                 @ApiParam("地址id") @RequestParam Long addressId,
                                 @ApiParam("支付方式 1 支付宝 2 微信") @RequestParam Integer payType,
                                 @ApiParam("备注信息") String remark) {
        ZslStoreCommodity zslStoreCommodity = iZslStoreCommodityService.selectById(commodityId);
        ZslShippingAddress zslShippingAddress = iZslShippingAddressService.selectById(addressId);
        ZslOrder zslOrder = new ZslOrder(null, null,0, 1, BaseContextHandler.getUserID(), zslStoreCommodity.getUserId()
                , BigDecimal.valueOf(0), zslStoreCommodity.getPrice().multiply(BigDecimal.valueOf(count)), payType,
                remark, null, null, zslShippingAddress.getName(), zslShippingAddress.getPhone(),
                zslShippingAddress.getProvince(), zslShippingAddress.getCity(), zslShippingAddress.getDistrict(),
                zslShippingAddress.getAddress(),
                iZslStoreService.selectById(zslStoreCommodity.getStoreId()).getName(), 0,
                null, null);
        iZslOrderService.insert(zslOrder);
        iZslOrderCommodtyService.insert(new ZslOrderCommodty(0, BaseContextHandler.getUserID(), commodityId,
                zslOrder.getId(), zslStoreCommodity.getName(), null, zslStoreCommodity.getPrice(), count,
                zslStoreCommodity.getPrice().multiply(BigDecimal.valueOf(count)), zslStoreCommodity.getPicUrl()));
        return new ReturnObject<>(0, "下单成功请付款", zslOrder.getId());
    }

    @ApiOperation("购物车下单(商品数量跟随购物车中的数量走)")
    @RequestMapping(value = "/addShoppingOrder", method = RequestMethod.POST)
    public ReturnObject addShoppingOrder(@ApiParam("商品id") @RequestParam Long[] commodityIds,
                                         @ApiParam("地址id") @RequestParam Long addressId,
                                         @ApiParam("支付方式 1 支付宝 2 微信") @RequestParam Integer payType,
                                         @ApiParam("备注信息") String remark) {
        //获取购物车中的商品
        List<ZslCar> zslCars = iZslCarService.selectList(new EntityWrapper<ZslCar>().eq("info.user_id",
                BaseContextHandler.getUserID()).in("info.commodity_id", commodityIds));
        BigDecimal totalPrice = BigDecimal.valueOf(0);
        ZslStoreCommodity zslStoreCommodity = iZslStoreCommodityService.selectById(zslCars.get(0).getCommodityId());
        for (int i = 0; i < zslCars.size(); i++) {
            if (zslCars.get(i).getSellerUserId().longValue() != zslCars.get(0).getSellerUserId().longValue()) {
                return new ReturnObject<>(1, "不同商家商品请分开下单");
            }
            totalPrice =
                    totalPrice.add(zslStoreCommodity.getPrice().multiply(BigDecimal.valueOf(zslCars.get(i).getCount())));

        }
        ZslShippingAddress zslShippingAddress = iZslShippingAddressService.selectById(addressId);
        ZslOrder zslOrder = new ZslOrder(null, null, 0,1, BaseContextHandler.getUserID(), zslCars.get(0).getSellerUserId()
                , BigDecimal.valueOf(0), totalPrice, payType, remark, null, null, zslShippingAddress.getName(),
                zslShippingAddress.getPhone(), zslShippingAddress.getProvince(), zslShippingAddress.getCity(),
                zslShippingAddress.getDistrict(), zslShippingAddress.getAddress(),
                iZslStoreService.selectById(zslStoreCommodity.getStoreId()).getName(),0, null, null);
        iZslOrderService.insert(zslOrder);
        for (ZslCar info : zslCars) {
            zslStoreCommodity = iZslStoreCommodityService.selectById(info.getCommodityId());
            iZslOrderCommodtyService.insert(new ZslOrderCommodty(0, BaseContextHandler.getUserID(),
                    info.getCommodityId(), zslOrder.getId(), zslStoreCommodity.getName(), null,
                    zslStoreCommodity.getPrice(), info.getCount(),
                    zslStoreCommodity.getPrice().multiply(BigDecimal.valueOf(info.getCount())),
                    zslStoreCommodity.getPicUrl()));
        }
        //删除购物车
        iZslCarService.delete(new EntityWrapper<ZslCar>().eq("user_id", BaseContextHandler.getUserID()).in(
                "commodity_id", commodityIds));
        return new ReturnObject<>(0, "下单成功请付款", zslOrder.getId());
    }


    @ApiOperation("用户获取本人订单分页")
    @RequestMapping(value = "/getMyPage", method = RequestMethod.POST)
    public ReturnObject<List<ZslOrder>> getMyPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                  @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                  @ApiParam("状态1 待付款 2 待发货 3 待确认收货 4 交易成功 5 交易关闭 6已评价") Integer state) {
        EntityWrapper<ZslOrder> ew = new EntityWrapper<>();
        if (state != null) {
            ew.eq("state", state);
        }
        ew.eq("user_id", BaseContextHandler.getUserID());
        ew.orderBy("crt_time", false);
        Page<ZslOrder> obj = iZslOrderService.selectPage(new Page<>(offset, limit), ew);
        for (int i = 0; i < obj.getRecords().size(); i++) {
            obj.getRecords().get(i).setCommodties(iZslOrderCommodtyService.selectList(new EntityWrapper<ZslOrderCommodty>().eq(
                    "order_id", obj.getRecords().get(i).getId())));

        }
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("用户订单详情")
    @RequestMapping(value = "/getMyInfo", method = RequestMethod.POST)
    public ReturnObject<ZslOrder> getMyInfo(@ApiParam("id") @RequestParam Long id) {
        ZslOrder info = iZslOrderService.selectById(id);
        info.setCommodties(iZslOrderCommodtyService.selectList(new EntityWrapper<ZslOrderCommodty>().eq(
                "order_id", info.getId())));
        info.setZslStore(iZslStoreService.selectById(iSysUserService.selectById(info.getSellerUserId()).getStoreId()));
        return new ReturnObject<>(0, "获取成功", info);
    }

    @ApiOperation("商户获取售卖的订单分页")
    @RequestMapping(value = "/getMerchantPage", method = RequestMethod.POST)
    public ReturnObject<List<ZslOrder>> getMerchantPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                        @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                        @ApiParam("状态1 待付款 2 待发货 3 待确认收货 4 交易成功 5 交易关闭 6已评价") Integer state) {
        EntityWrapper<ZslOrder> ew = new EntityWrapper<>();
        if (state != null) {
            ew.eq("state", state);
        }
        ew.eq("seller_user_id", BaseContextHandler.getUserID());
        ew.orderBy("crt_time", false);
        Page<ZslOrder> obj = iZslOrderService.selectPage(new Page<>(offset, limit), ew);
        for (int i = 0; i < obj.getRecords().size(); i++) {
            obj.getRecords().get(i).setCommodties(iZslOrderCommodtyService.selectList(new EntityWrapper<ZslOrderCommodty>().eq(
                    "order_id", obj.getRecords().get(i).getId())));

        }
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }


    @ApiOperation("商家设置已发货")
    @RequestMapping(value = "/shipped", method = RequestMethod.POST)
    public ReturnObject<ZslOrder> shipped(@ApiParam("订单id") @RequestParam Long id) {

        ZslOrder info = iZslOrderService.selectById(id);
        if (info.getState() == 2) {
            info.setState(3);
            iZslOrderService.updateById(info);
        } else {
            return new ReturnObject<>(1, "该订单状态错误，请刷新页面");
        }

        return new ReturnObject<>(0, "设置成功");
    }

    @ApiOperation("用户设置已收货")
    @RequestMapping(value = "/receiving", method = RequestMethod.POST)
    public ReturnObject<ZslOrder> receiving(@ApiParam("订单id") @RequestParam Long id) {

        ZslOrder info = iZslOrderService.selectById(id);
        if (info.getState() == 3) {
            info.setState(4);
            iZslOrderService.updateById(info);
            //增加商家佣金
            SysUser sysUser = iSysUserService.selectById(info.getSellerUserId());
            sysUser.setCanCarry(sysUser.getCanCarry().add(info.getTotalPrice()));
            iSysUserService.updateById(sysUser);
        } else {
            return new ReturnObject<>(1, "该订单状态错误，请刷新页面");
        }
        return new ReturnObject<>(0, "设置成功", null);
    }

    @ApiOperation("用户设置提交评价")
    @RequestMapping(value = "/orderRate", method = RequestMethod.POST)
    public ReturnObject<ZslOrder> orderRate(@ApiParam("订单id") @RequestParam Long id,
                                            @ApiParam("评价内容") @RequestParam(defaultValue = "默认评价") String content,
                                            @ApiParam("评分等级 0.0-5.0") @RequestParam(defaultValue = "5") Double grade) {

        ZslOrder info = iZslOrderService.selectById(id);
        if (info.getState() == 4) {
            info.setState(6);
            iZslOrderService.updateById(info);
            List<ZslOrderCommodty> commodties =
                    iZslOrderCommodtyService.selectList(new EntityWrapper<ZslOrderCommodty>().eq("order_id", id));
            for (ZslOrderCommodty orderCommodty : commodties) {
                iZslOrderEvaluateService.insert(new ZslOrderEvaluate(0, content, grade,
                        BaseContextHandler.getUserID(), id, orderCommodty.getCommodityId(), null));
                //计算商品平均评分
                ZslStoreCommodity zslStoreCommodity =
                        iZslStoreCommodityService.selectById(orderCommodty.getCommodityId());
                zslStoreCommodity.setGrade(iZslOrderEvaluateService.gradeAvg(orderCommodty.getCommodityId()));
                iZslStoreCommodityService.updateById(zslStoreCommodity);
            }
        } else {
            return new ReturnObject<>(1, "该订单状态错误，请刷新页面");
        }
        return new ReturnObject<>(0, "设置成功", null);
    }


    @IgnoreAuth
    @ApiOperation("获取商品的评价列表")
    @RequestMapping(value = "/orderEvaluate", method = RequestMethod.POST)
    public ReturnObject<List<ZslOrderEvaluate>> commodityOrder(@ApiParam("商品id") @RequestParam Long id) {

        List<ZslOrderEvaluate> list = iZslOrderEvaluateService.selectList(new EntityWrapper<ZslOrderEvaluate>().eq(
                "commodity_id", id).orderBy("crt_time", false));
        return new ReturnObject<>(0, "获取成功", list);
    }


    @ApiOperation("店铺获取用户评价列表")
    @RequestMapping(value = "/commodityOrderEvaluate", method = RequestMethod.POST)
    public ReturnObject<List<ZslOrderEvaluate>> commodityOrderEvaluate(@ApiParam("每页条数") @RequestParam(defaultValue =
            "10") int limit,
                                                                       @ApiParam("页数") @RequestParam(defaultValue =
                                                                               "1") int offset,
                                                                       @ApiParam("状态1 已回复 2 未回复 3 全部") Integer state) {

        EntityWrapper<ZslOrderEvaluate> ew = new EntityWrapper<>();
        if (state == 1) {
            ew.isNotNull("reply_content");
        } else if (state == 2) {
            ew.isNull("reply_content");
        }
        ew.in("commodity_id", iZslStoreCommodityService.selectObjs(new EntityWrapper<ZslStoreCommodity>().eq("user_id"
                , BaseContextHandler.getUserID()).setSqlSelect("id")));
        ew.orderBy("crt_time", false);
        Page<ZslOrderEvaluate> obj = iZslOrderEvaluateService.selectPage(new Page<>(offset, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }


    @ApiOperation("店铺回复评论")
    @RequestMapping(value = "/evaluateReply", method = RequestMethod.POST)
    public ReturnObject evaluateReply(@ApiParam("评论id") Long id,
                                      @ApiParam("回复内容") String replyContent) {

        ZslOrderEvaluate info = iZslOrderEvaluateService.selectById(id);
        info.setReplyContent(replyContent);
        iZslOrderEvaluateService.updateById(info);
        return new ReturnObject<>(0, "回复成功");
    }


    @ApiOperation("商品成交记录")
    @IgnoreAuth
    @RequestMapping(value = "/getTransactionRecord", method = RequestMethod.POST)
    public ReturnObject<List<TransactionRecord>> getTransactionRecord(@ApiParam("商品id") Long commodityId) {

        List<TransactionRecord> trs= new ArrayList<TransactionRecord>();
        TransactionRecord transactionRecord=new TransactionRecord();
        List<ZslOrderCommodty>  list = iZslOrderCommodtyService.selectList(new EntityWrapper<ZslOrderCommodty>().eq("commodity_id",commodityId));
         if(list!=null&&list.size()>0){
             for(ZslOrderCommodty zslOrderCommodty:list){
                 transactionRecord.setPurchaser(iSysUserService.selectById(zslOrderCommodty.getUserId()).getUsername());
                 transactionRecord.setNumber(zslOrderCommodty.getCount());
                 transactionRecord.setTime(zslOrderCommodty.getCrtTime());
                 ZslStoreCommodity commodity=iZslStoreCommodityService.selectById(zslOrderCommodty.getCommodityId());
                 transactionRecord.setGoogdSpecification(commodity.getOrigin());
                 trs.add(transactionRecord);
             }
         }

        return new ReturnObject<>(0, "获取成功",trs);
    }


}

